import CryptoJS from 'crypto-js'
import { isBase64 } from './basicHelper'

/**
 * 字符加密
 * @param value 需要加密的字符
 * @return 密文
 */
export function encrypt(value: string, keyStr: string, ivStr: string) {
  if (keyStr == '' || ivStr == '') {
    console.info('encrypt', 'keyStr or ivStr is empty string')
    return value
  }

  /**
   *  //分别生成头尾8位的随机值
   *  var head = Math.ceil((Math.random() + 1) * 10000000);
   *  var tail = Math.ceil((Math.random() + 1) * 10000000);
   *  //把头尾拼接到明文上面
   *  var text = head + value + tail;
   * 倒序输出
   *  var reverseText = text.split('').reverse().join('');
   */
  let reverseText = value

  // aes加密
  let key = CryptoJS.enc.Utf8.parse(keyStr)
  let iv = CryptoJS.enc.Utf8.parse(ivStr)
  let srcs = CryptoJS.enc.Utf8.parse(reverseText)
  let encrypted = CryptoJS.AES.encrypt(srcs, key, {
    iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  })

  // 15850747305
  let encryptedStr = encrypted.ciphertext.toString()
  let hexStr = CryptoJS.enc.Hex.parse(encryptedStr)
  let encryptedBase = CryptoJS.enc.Base64.stringify(hexStr)
  return encryptedBase
}

/**
 * 解密
 * @encryptedStr 密文 必须base64编码字符串
 */
function decrypt(encryptedStr: string, keyStr: string, ivStr: string): string {
  if (keyStr == '' || ivStr == '') {
    console.info('decrypt', 'keyStr or ivStr is empty string')
    return ''
  }
  if (!isBase64(encryptedStr)) {
    return encryptedStr
  }
  let key = CryptoJS.enc.Utf8.parse(keyStr)
  let iv = CryptoJS.enc.Utf8.parse(ivStr)
  let decryptedStr = ''
  try {
    let decrypt = CryptoJS.AES.decrypt(encryptedStr, key, {
      iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    })
    decryptedStr = CryptoJS.enc.Utf8.stringify(decrypt).toString()

    /**
     * decryptedStr = decryptedStr.split("").reverse();
     * decryptedStr.splice(0, 8);
     * decryptedStr.splice(-8, 8);
     */
    // decryptedStr = decryptedStr.join('');
  } catch (error) {
    console.error('decrypt has error', error)
  }

  // console.error('decryptedStr',decryptedStr.join(""));
  return decryptedStr
}

export default {
  decrypt,
  encrypt,
}
